package com.lianxi.Courses.controller;

import com.github.pagehelper.PageInfo;
import com.lianxi.Courses.constant.CommentConstant;
import com.lianxi.Courses.constant.ResponseCodeConstant;
import com.lianxi.Courses.entity.*;
import com.lianxi.Courses.exception.*;
import com.lianxi.Courses.service.*;
import com.lianxi.Courses.util.ResponseResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/course")
public class CourseController {
    @Autowired
    private CourseService courseService;
    @Autowired
    private CourseTypeService typeService;
    @Autowired
    private ResourceService resourceService;
    @Autowired
    private CommentService commentService;
    @Autowired
    private UserResourceService userResourceService;
    @Autowired
    private GoldPointsService goldPointsService;


    @RequestMapping("/findAll")
    public ModelAndView findAll(Course courseParam, String pageNo, String pageSize) {
        ModelAndView mav = new ModelAndView();
        try {
//            List<CourseType> types = typeService.findAll();
            List<CourseType> types = typeService.findLeafTypes();
            mav.addObject("types", types);
            PageInfo<Course> coursePage = courseService.findPage(courseParam, pageNo, pageSize);
            mav.addObject("coursePage", coursePage);
            mav.addObject("courseParam", courseParam);

            mav.setViewName("backend/back_courseSet");
        } catch (Exception e) {
            e.printStackTrace();
            mav.addObject("errorMessage", "查询课程列表失败，请稍后重试");
            mav.setViewName("backend/back_courseSet");
        }
        return mav;
    }






    @RequestMapping("/addCourse")
    @ResponseBody
    public ResponseResult addCourse(String courseName, String courseInfo, String author, @RequestParam("file") CommonsMultipartFile file, String recommendationGrade, String courseTypeId, HttpSession session) {
        ResponseResult result = new ResponseResult();

        try {
            courseService.addCourse(courseName, courseInfo, author, file, recommendationGrade, courseTypeId, session);
            result.setMessage("成功");
            result.setResponseCode(ResponseCodeConstant.RESPONSE_CODE_SUCCESS);
        } catch (RequestParameterErrorException e) {
            result.setMessage(e.getMessage());
            result.setResponseCode(ResponseCodeConstant.RESPONSE_CODE_REQUEST_PARAMETER_ERROR);
        } catch (CourseExistException e) {
            result.setMessage(e.getMessage());
            result.setResponseCode(ResponseCodeConstant.RESPONSE_CODE_FAIL);
        } catch (FileUploadErrorException e) {
            result.setMessage(e.getMessage());
            result.setResponseCode(ResponseCodeConstant.RESPONSE_CODE_FAIL);
        } catch (Exception e) {
            result.setMessage("服务器内部异常");
            result.setResponseCode(ResponseCodeConstant.RESPONSE_CODE_FAIL);
        }

        return result;
    }




    @RequestMapping("/findById")
    @ResponseBody
    public ResponseResult findById(String id){
        ResponseResult result = new ResponseResult();

        try {
            Course course = courseService.findById(id);
            result.setMessage("成功");
            result.setResponseCode(ResponseCodeConstant.RESPONSE_CODE_SUCCESS);
            result.setReturnObject(course);
        } catch (RequestParameterErrorException e) {
            result.setMessage(e.getMessage());
            result.setResponseCode(ResponseCodeConstant.RESPONSE_CODE_REQUEST_PARAMETER_ERROR);
        } catch (Exception e) {
            result.setMessage("服务器内部异常");
            result.setResponseCode(ResponseCodeConstant.RESPONSE_CODE_FAIL);
        }
        return result;
    }


    @RequestMapping("/modifyStatus")
    @ResponseBody
    public ResponseResult modifyStatus(String id, String status) {
        ResponseResult result = new ResponseResult();
        try {
            courseService.modifyStatus(id, status);
            result.setMessage("成功");
            result.setResponseCode(ResponseCodeConstant.RESPONSE_CODE_SUCCESS);
        } catch (RequestParameterErrorException e) {
            result.setMessage(e.getMessage());
            result.setResponseCode(ResponseCodeConstant.RESPONSE_CODE_REQUEST_PARAMETER_ERROR);
        } catch (Exception e) {
            result.setMessage("服务器内部异常");
            result.setResponseCode(ResponseCodeConstant.RESPONSE_CODE_FAIL);
        }
        return result;
    }



    @RequestMapping("/modifyCourse")
    @ResponseBody
    public ResponseResult modifyCourse(String id,String courseName, String courseInfo, String author, @RequestParam("file") CommonsMultipartFile file, String recommendationGrade, String courseTypeId, HttpSession session){
        ResponseResult result = new ResponseResult();

        try {
            courseService.modifyCourse(id,courseName, courseInfo, author, file, recommendationGrade, courseTypeId, session);
            result.setMessage("成功");
            result.setResponseCode(ResponseCodeConstant.RESPONSE_CODE_SUCCESS);
        } catch (RequestParameterErrorException e) {
            result.setMessage(e.getMessage());
            result.setResponseCode(ResponseCodeConstant.RESPONSE_CODE_REQUEST_PARAMETER_ERROR);
        } catch (CourseExistException e) {
            result.setMessage(e.getMessage());
            result.setResponseCode(ResponseCodeConstant.RESPONSE_CODE_FAIL);
        } catch (FileUploadErrorException e) {
            result.setMessage(e.getMessage());
            result.setResponseCode(ResponseCodeConstant.RESPONSE_CODE_FAIL);
        } catch (Exception e) {
            result.setMessage("服务器内部异常");
            result.setResponseCode(ResponseCodeConstant.RESPONSE_CODE_FAIL);
        }

        return result;
    }

    @RequestMapping("/findByIdAll")
    public ModelAndView findByIdAll(String id){
        ModelAndView mav = new ModelAndView();
        try {
            Course course = courseService.findByIdAll(id);
            List<Course> courses =courseService.findByTypeId(String.valueOf(course.getCourseType03().getId()));

            mav.addObject("course",course);
            mav.addObject("courses",courses);
            mav.setViewName("backend/front_course");
        } catch (RequestParameterErrorException e) {
            mav.addObject("UserMsg", e);
            mav.setViewName("backend/front_course");
        }catch (Exception e) {
            e.printStackTrace();
            mav.addObject("UserMsg", "服务器内部异常");
            mav.setViewName("backend/front_course");
        }
        return mav;
    }

    //根据资源id找
    @RequestMapping("/findVideo")
    public ModelAndView findVideo(String id, String pageNo, String pageSize) {
        ModelAndView mav = new ModelAndView();

        try {
            Resource resource = resourceService.findById(id);

            //返回评论分页
            Comment comment =new Comment();
            comment.setStatus(CommentConstant.COMMENT_ENABLE);
            comment.setResourceId(Integer.valueOf(id));
            PageInfo<Comment> commentPage = commentService.findPage(comment,pageNo, pageSize);

            //返回当前课程
            Course course =resourceService.findByIdForCourse(id);

            //返回前三课程
            List<Course> courses =courseService.findByTypeId(String.valueOf(course.getCourseTypeId()));

            mav.addObject("course", course);
            mav.addObject("commentPage",commentPage);
            mav.addObject("courses",courses);
            mav.setViewName("backend/front_courseDetail");
        } catch (RequestParameterErrorException e) {
            mav.addObject("errorMessage", e.getMessage());
            mav.setViewName("backend/front_course");
        }catch (Exception e) {
            mav.addObject("UserMsg", "服务器内部异常");
            mav.setViewName("backend/front_course");
        }


        return mav;
    }

    //买资源
    @RequestMapping("/addBuyResource")
    @ResponseBody
    public ResponseResult addBuyResource(HttpSession session, String resourceId){
        ResponseResult result = new ResponseResult();

        User user = (User) session.getAttribute("user");
        String userId = String.valueOf(user.getId());
        System.out.println(userId);
        try {
            if (!userResourceService.yesOrNo(userId,resourceId)){
                userResourceService.addBuyResource(userId,resourceId,session);
                result.setMessage("购买成功");
                result.setResponseCode(ResponseCodeConstant.RESPONSE_CODE_SUCCESS);
            }else {
                result.setMessage("您已拥有");
                result.setResponseCode(ResponseCodeConstant.RESPONSE_CODE_SUCCESS);
            }
            user = goldPointsService.findGoldPoints(userId,session);
            session.setAttribute("user",user);
        } catch (RequestParameterErrorException e) {
            result.setMessage(e.getMessage());
            result.setResponseCode(ResponseCodeConstant.RESPONSE_CODE_SUCCESS);
        } catch (UserResourceErrorException e) {
            result.setMessage(e.getMessage());
            result.setResponseCode(ResponseCodeConstant.RESPONSE_CODE_FAIL);
        } catch (GoldPointsErrorException e) {
            result.setMessage("金币或积分不足");
            result.setResponseCode(ResponseCodeConstant.RESPONSE_CODE_REQUEST_PARAMETER_ERROR);
        }catch (Exception e) {
            result.setMessage("服务器内部异常");
            result.setResponseCode(ResponseCodeConstant.RESPONSE_CODE_FAIL);
        }

        return result;
    }

    @RequestMapping("/getTop4Courses")
    @ResponseBody
    public ResponseResult getTop4Courses() {
        ResponseResult result = new ResponseResult();
        try {
            // 获取所有最小类别
            List<CourseType> leafTypes = typeService.findLeafTypes();
            List<Map<String, Object>> typeCoursesList = new ArrayList<>();

            // 为每个最小类别获取点击量前四的课程
            for (CourseType leafType : leafTypes) {
                Map<String, Object> typeCoursesMap = new HashMap<>();
                typeCoursesMap.put("typeId", leafType.getId());
                typeCoursesMap.put("typeName", leafType.getTypeName());

                // 获取该类别下的课程
                List<Course> top4Courses = courseService.findByTypeId(String.valueOf(leafType.getId()));
                typeCoursesMap.put("top4Courses", top4Courses);
                typeCoursesList.add(typeCoursesMap);
            }

            result.setMessage("成功");
            result.setResponseCode(ResponseCodeConstant.RESPONSE_CODE_SUCCESS);
            result.setReturnObject(typeCoursesList);
        } catch (Exception e) {
            e.printStackTrace();
            result.setMessage("服务器内部异常");
            result.setResponseCode(ResponseCodeConstant.RESPONSE_CODE_FAIL);
        }
        return result;
    }




    @RequestMapping("/getAllCourses")
    @ResponseBody
    public ResponseResult getAllCourses() {
        ResponseResult result = new ResponseResult();
        try {
            // 获取所有课程，按点击量从小到大排序
            List<Course> allCourses = courseService.getAllCourses();

            result.setMessage("成功");
            result.setResponseCode(ResponseCodeConstant.RESPONSE_CODE_SUCCESS);
            result.setReturnObject(allCourses);
        } catch (RequestParameterErrorException e) {
            result.setMessage(e.getMessage());
            result.setResponseCode(ResponseCodeConstant.RESPONSE_CODE_REQUEST_PARAMETER_ERROR);
        } catch (Exception e) {
            e.printStackTrace();
            result.setMessage("服务器内部异常");
            result.setResponseCode(ResponseCodeConstant.RESPONSE_CODE_FAIL);
        }
        return result;
    }
}











